const tableData = {
  getMaxCols(data) {
    // 计算最大列数
    const maxCols = data.reduce((max, row) => {
      const actualCols = row.reduce((sum, cell) => {
        if (!cell) return sum;
        return sum + (cell.colSpan || 1);
      }, 0);
      return Math.max(max, actualCols);
    }, 0);
    return maxCols;
  },
  rectangleTableDataByLine(data) {
    // TODO: 不知道为什么，这里会报错，暂时不知道原因
    if (!data || !data.length) return [];
    for (let i = 0; i < data.length; i++) {
      const row = data[i];
      for (let j = 0; j < row.length; j++) {
        const cell = row[j];
        if (!cell) continue;
        debugger
        if (cell.colSpan && cell.colSpan > 1) {
          const insertCount = cell.colSpan - 1;
          for (let c = 0; c < insertCount; c++) {
            row.splice(j + 1, 0, null);
          }
        }
        if (cell.rowSpan && cell.rowSpan > 1) {
          const insertCount = cell.rowSpan - 1;
          for (let r = 0; r < insertCount; r++) {
            data[i + r + 1].splice(j, 0, null);
          }
        }
      }
    }
    return data;
  },
  // 格式化初始数据 统一转化为标准矩形，对于不存在的项，用null填充
  rectangleTableData(data) {
    if (!data || !data.length) return [];

    // 计算最大列数
    const maxCols = this.getMaxCols(data);

    // 创建新的矩形数据结构
    const formattedData = Array(data.length)
      .fill()
      .map(() => Array(maxCols).fill(null));
    let rowIndex = 0;

    // 创建一个二维数组来跟踪已被占用的位置
    const occupiedPositions = Array(data.length)
      .fill()
      .map(() => Array(maxCols).fill(false));

    while (rowIndex < data.length) {
      const row = data[rowIndex];
      let colIndex = 0;

      // 填充当前行数据
      for (let i = 0; i < row.length; i++) {
        const cell = row[i];
        if (!cell) continue;

        // 找到下一个可用的列位置
        while (colIndex < maxCols && occupiedPositions[rowIndex][colIndex]) {
          colIndex++;
        }

        if (colIndex >= maxCols) break;

        // 设置当前单元格
        formattedData[rowIndex][colIndex] = cell;
        occupiedPositions[rowIndex][colIndex] = true;

        // 处理列合并
        const colSpan = cell.colSpan || 1;
        for (let c = 1; c < colSpan; c++) {
          if (colIndex + c < maxCols) {
            occupiedPositions[rowIndex][colIndex + c] = true;
          }
        }

        // 处理行合并
        const rowSpan = cell.rowSpan || 1;
        for (let r = 1; r < rowSpan; r++) {
          if (rowIndex + r < data.length) {
            // 标记被行合并占据的所有位置
            for (let c = 0; c < colSpan; c++) {
              if (colIndex + c < maxCols) {
                occupiedPositions[rowIndex + r][colIndex + c] = true;
              }
            }
          }
        }

        colIndex += colSpan;
      }
      rowIndex++;
    }

    return formattedData;
  },
  // 渲染数据到表格
  renderToTable(data, table) {
    console.log('byLine::', this.rectangleTableDataByLine(data));
    const formattedData = this.rectangleTableData(data);
    console.log(formattedData);
    // 清空现有表格内容
    table.innerHTML = "";

    // 添加 colgroup
    const maxCols = this.getMaxCols(data);
    const colgroup = document.createElement("colgroup");
    Array(maxCols)
      .fill()
      .forEach(() => {
        const col = document.createElement("col");
        col.style.minWidth = "100px";
        colgroup.appendChild(col);
      });
    table.appendChild(colgroup);
    // 遍历数据并创建表格行和单元格
    data.forEach((rowData, rowIndex) => {
      const row = table.insertRow();

      rowData.forEach((cellData) => {
        if (!cellData) return;
        const cell = row.insertCell();
        cell.textContent = cellData.value;

        // 设置合并属性
        if (cellData.rowSpan) {
          cell.rowSpan = cellData.rowSpan;
        }
        if (cellData.colSpan) {
          cell.colSpan = cellData.colSpan;
        }
      });
    });
  },

  // 从表格获取数据
  getTableData(table) {
    const data = [];

    // 遍历表格行
    for (let i = 0; i < table.rows.length; i++) {
      const row = table.rows[i];
      const rowData = [];
      // 遍历行中的单元格
      for (let j = 0; j < row.cells.length; j++) {
        const cell = row.cells[j];
        const cellData = {
          value: cell.textContent,
        };

        // 添加合并属性
        if (cell.rowSpan > 1) {
          cellData.rowSpan = cell.rowSpan;
        }
        if (cell.colSpan > 1) {
          cellData.colSpan = cell.colSpan;
        }

        rowData.push(cellData);
      }

      data.push(rowData);
    }

    return data;
  },

  // 获取JSON字符串
  getTableDataJson(table) {
    return JSON.stringify(this.getTableData(table));
  },
};
